<template>
  <div class="reviews-container">
    <h2 style="text-align: center;">评价管理</h2>

    <!-- 添加评价表单 -->
    <div class="add-review-form">
      <el-form :model="reviewForm" label-width="100px">
        <el-form-item label="预约ID" prop="appointmentId" required>
          <el-input v-model.number="reviewForm.appointmentId" placeholder="请输入预约ID"></el-input>
        </el-form-item>
        <el-form-item label="陪诊员ID" prop="escortId" required>
          <el-input v-model.number="reviewForm.escortId" placeholder="请输入陪诊员ID"></el-input>
        </el-form-item>
        <el-form-item label="评分" prop="rating" required>
          <el-rate v-model="reviewForm.rating" :max="5" show-score></el-rate>
        </el-form-item>
        <el-form-item label="评价内容" prop="content">
          <el-input
              v-model="reviewForm.content"
              type="textarea"
              :rows="4"
              placeholder="请输入评价内容(最多500字)"
              maxlength="500"
              show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="预约ID" prop="appointmentId" required>
          <el-input
              v-model.number="reviewForm.appointmentId"
              placeholder="请输入预约ID"
              :disabled="!!$route.query.appointmentId"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitReview">提交评价</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 评价筛选 -->
    <div class="filter-section">
      <el-form :inline="true" :model="filterParams">
        <el-form-item label="用户ID">
          <el-input v-model.number="filterParams.userId" placeholder="用户ID"></el-input>
        </el-form-item>
        <el-form-item label="陪诊员ID">
          <el-input v-model.number="filterParams.escortId" placeholder="陪诊员ID"></el-input>
        </el-form-item>
        <el-form-item label="评分范围">
          <el-input-number v-model="filterParams.minRating" :min="1" :max="5" placeholder="最低分"></el-input-number>
          <span style="margin: 0 10px;">至</span>
          <el-input-number v-model="filterParams.maxRating" :min="1" :max="5" placeholder="最高分"></el-input-number>
        </el-form-item>
        <el-form-item label="回复状态">
          <el-select v-model="filterParams.replied" placeholder="全部">
            <el-option label="全部" :value="null"></el-option>
            <el-option label="已回复" :value="true"></el-option>
            <el-option label="未回复" :value="false"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchReviews">筛选</el-button>
          <el-button @click="resetFilters">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 评价统计 -->
    <div class="review-stats">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-statistic title="总评价数" :value="total"></el-statistic>
        </el-col>
        <el-col :span="6">
          <el-statistic title="平均评分" :value="avgRating" :precision="1"></el-statistic>
        </el-col>
        <el-col :span="6">
          <el-statistic title="已回复" :value="repliedCount"></el-statistic>
        </el-col>
        <el-col :span="6">
          <el-statistic title="未回复" :value="total - repliedCount"></el-statistic>
        </el-col>
      </el-row>
    </div>

    <!-- 评价列表 -->
    <el-table :data="reviews" style="width: 100%" border>
      <el-table-column prop="id" label="评价ID" width="90"></el-table-column>
      <el-table-column prop="userName" label="用户" width="90"></el-table-column>
      <el-table-column prop="escortId" label="陪诊员ID" width="90"></el-table-column>
      <el-table-column prop="escortName" label="陪诊员姓名" width="110"></el-table-column>
      <el-table-column label="评分" width="160">
        <template #default="{row}">
          <el-rate v-model="row.rating" disabled show-score></el-rate>
        </template>
      </el-table-column>
      <el-table-column prop="content" label="评价内容"></el-table-column>
      <el-table-column prop="createTime" label="评价时间" width="180"></el-table-column>
      <el-table-column label="回复状态" width="120">
        <template #default="{row}">
          <el-tag :type="row.replyStatus ? 'success' : 'warning'">
            {{ row.replyStatus ? '已回复' : '未回复' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" v-if="isEscort">
        <template #default="{row}">
          <el-button
              size="small"
              type="primary"
              v-if="!row.replyStatus"
              @click="showReplyDialog(row)"
          >
            回复
          </el-button>
          <el-button
              size="small"
              type="info"
              v-else
              @click="showReplyDialog(row)"
          >
            查看回复
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        layout="prev, pager, next"
        :total="total"
        v-model:current-page="currentPage"
        :page-size="pageSize"
        @current-change="fetchReviews"
        style="margin-top: 20px"
    />

    <!-- 回复评价对话框 -->
    <el-dialog v-model="replyDialogVisible" :title="replyDialogTitle">
      <el-form :model="replyForm">
        <el-form-item label="回复内容">
          <el-input
              v-model="replyForm.replyContent"
              type="textarea"
              :rows="4"
              placeholder="请输入回复内容"
              :disabled="isViewOnly"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="replyDialogVisible = false">取消</el-button>
        <el-button
            type="primary"
            @click="submitReply"
            v-if="!isViewOnly"
        >
          提交回复
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRoute } from 'vue-router'

const route = useRoute()

const BASE_URL = 'http://localhost:8080'

// 用户角色判断
const isEscort = ref(false) // 假设根据登录信息设置

// 评价表单
const reviewForm = ref({
  appointmentId: null,
  escortId: null,
  rating: 5,
  content: ''
})

// 筛选参数
const filterParams = ref({
  userId: null,
  escortId: null,
  minRating: null,
  maxRating: null,
  replied: null
})

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 统计数据
const avgRating = ref(0)
const repliedCount = ref(0)

// 评价列表
const reviews = ref([])

// 回复对话框
const replyDialogVisible = ref(false)
const replyForm = ref({
  reviewId: null,
  replyContent: ''
})
const isViewOnly = ref(false)
const replyDialogTitle = computed(() =>
    isViewOnly.value ? '查看回复' : '回复评价'
)

// 修改fetchReviews方法
const fetchReviews = async () => {
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      ...filterParams.value
    }

    // 移除值为null的参数
    Object.keys(params).forEach(key => {
      if (params[key] === null || params[key] === '') {
        delete params[key]
      }
    })

    // 使用正确的端点路径
    const res = await axios.get(`${BASE_URL}/v1/user/reviews/page`, { params })

    if (res.data.state === 2000) {
      reviews.value = res.data.data.list || []
      total.value = res.data.data.total || 0

      // 计算统计数据
      if (reviews.value.length > 0) {
        const sum = reviews.value.reduce((acc, cur) => acc + cur.rating, 0)
        avgRating.value = sum / reviews.value.length
        repliedCount.value = reviews.value.filter(r => r.replyStatus).length
      }
    } else {
      ElMessage.error(res.data.msg)
    }
  } catch (error) {
    console.error('获取评价列表失败:', error)
    ElMessage.error(error.response?.data?.message || '获取评价列表失败')
  }
}

// 修改submitReview方法
const submitReview = async () => {
  try {
    const res = await axios.post(`${BASE_URL}/v1/user/reviews/add`, reviewForm.value)
    if (res.data.state === 2000) {
      ElMessage.success('评价提交成功')
      reviewForm.value = {
        appointmentId: null,
        escortId: null,
        rating: 5,
        content: ''
      }
      fetchReviews()
    } else {
      ElMessage.error(res.data.msg)
    }
  } catch (error) {
    console.error('提交评价失败:', error)
    ElMessage.error(error.response?.data?.message || '提交评价失败')
  }
}

// 修改submitReply方法
const submitReply = async () => {
  try {
    const res = await axios.post(`${BASE_URL}/v1/user/reviews/reply`, replyForm.value)
    if (res.data.state === 2000) {
      ElMessage.success('回复成功')
      replyDialogVisible.value = false
      fetchReviews()
    } else {
      ElMessage.error(res.data.msg)
    }
  } catch (error) {
    console.error('回复评价失败:', error)
    ElMessage.error(error.response?.data?.message || '回复评价失败')
  }
}
// 显示回复对话框
const showReplyDialog = (row) => {
  replyForm.value = {
    reviewId: row.id,
    replyContent: row.replyContent || ''
  }
  isViewOnly.value = !!row.replyStatus
  replyDialogVisible.value = true
}
// 重置筛选条件
const resetFilters = () => {
  filterParams.value = {
    userId: null,
    escortId: null,
    minRating: null,
    maxRating: null,
    replied: null
  }
  currentPage.value = 1
  fetchReviews()
}

onMounted(() => {
  fetchReviews()

  // 模拟根据登录信息设置角色
  // 实际项目中应从store或session中获取
  isEscort.value = false // 设为true测试陪诊员功能
})

// 新增初始化逻辑
  onMounted(() => {
    if (route.query.appointmentId) {
      reviewForm.value.appointmentId = Number(route.query.appointmentId)
    }
    if (route.query.escortId) {
      reviewForm.value.escortId = Number(route.query.escortId)
    }

  fetchReviews()
})
</script>

<style scoped>
.reviews-container {
  padding: 30px;
  background-color: #f5f7fa;
  color: #333;
  font-family: 'Helvetica Neue', Arial, sans-serif;
}

.add-review-form {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.filter-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.review-stats {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.el-table {
  margin-top: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.el-pagination {
  justify-content: center;
  margin-top: 20px;
}

.el-rate {
  display: inline-flex;
  align-items: center;
}
</style>